﻿using System;
using System.Collections.Generic;
using System.IO;

using Bpms.Common;

namespace Bpms.Config
{
    /// <summary>
    /// 数据库配置文件操作类
    /// </summary>
    public class DbConfigFileManager : BaseConfigFileManager
    {

        private static DbConfigInfo _configInfo;

        /// <summary>
        /// 锁对象
        /// </summary>
        private static object _lockHelper = new object();

        /// <summary>
        /// 文件修改时间
        /// </summary>
        private static DateTime _fileOldChange;




        /// <summary>
        /// 初始化文件修改时间和对象实例
        /// </summary>
        static DbConfigFileManager()
        {
            _fileOldChange = System.IO.File.GetLastWriteTime(ConfigFilePath);
            _configInfo = (DbConfigInfo)BaseConfigFileManager.DeserializeInfo(ConfigFilePath, typeof(DbConfigInfo));
            // _configinfo = new DbConfigInfo();
        }

        /// <summary>
        /// 当前配置类的实例
        /// </summary>
        public new static IConfigInfo ConfigInfo
        {
            get { return _configInfo; }
            set { _configInfo = (DbConfigInfo)value; }
        }



        /// <summary>
        /// 配置文件所在路径
        /// </summary>
        public static string fileName = null;


        /// <summary>
        /// 获取配置文件所在路径
        /// </summary>
        public new static string ConfigFilePath
        {
            get
            {
                if (fileName == null)
                {
                    fileName = Utility.GetMapPath("~/config/database.config");
                    if (!File.Exists(fileName))
                    {
                        //File.Create(filename);
                        ConfigInfo = new DbConfigInfo();
                        new DbConfigFileManager().SaveConfig();
                    }
                }

                return fileName;
            }

        }

        /// <summary>
        /// 加载配置类
        /// </summary>
        /// <returns></returns>
        public static DbConfigInfo LoadConfig()
        {
            ConfigInfo = BaseConfigFileManager.LoadConfig(ref _fileOldChange, ConfigFilePath, ConfigInfo);
            return ConfigInfo as DbConfigInfo;
        }

        /// <summary>
        /// 加载真正有效的配置类
        /// </summary>
        /// <returns></returns>
        public static DbConfigInfo LoadRealConfig()
        {
            ConfigInfo = BaseConfigFileManager.LoadConfig(ref _fileOldChange, ConfigFilePath, ConfigInfo, false);
            return ConfigInfo as DbConfigInfo;
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <returns></returns>
        public override bool SaveConfig()
        {
            return base.SaveConfig(ConfigFilePath, ConfigInfo);
        }


    }
}
